<!--  -->
<template>
  <div class="padding20">
    <!-- <h6>表格设计</h6> -->
    <p style="textalign: right; padding-right: 20px">
      <el-button icon="el-icon-back" type="text" @click="back">返回</el-button>
    </p>
    <div style="margin-bottom: 7px">编辑文件：{{ editFileName }}</div>
    <el-row :gutter="20">
      <el-col :span="16"
        ><div class="grid-content bg-purple">
          <editor
            ref="aceEditor"
            v-model="content"
            @init="editorInit"
            width="97%"
            height="700"
            lang="javascript"
            :theme="theme"
            :options="{
              enableBasicAutocompletion: true,
              enableSnippets: true,
              enableLiveAutocompletion: true,
              tabSize: 6,
              fontSize: 14,
              showPrintMargin: false, //去除编辑器里的竖线
            }"
          ></editor>
        </div>
        <div style="margin-top: 10px">
          <el-button type="primary" @click="save">保存内容</el-button>
        </div>
      </el-col>
      <el-col :span="8"
        ><div class="grid-content bg-purple">
          <div>当前目录：{{ currentPath }}</div>
          <el-table
            ref="table"
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="id"
            border
            :show-header="false"
            height="700px"
          >
            <el-table-column prop="fileName" :show-overflow-tooltip="true">
              <template slot-scope="scope"
                ><div @click="handlerClick(scope.row)" style="cursor: pointer">
                  <i
                    class="el-icon-folder"
                    v-if="scope.row.directoryFlag == '0'"
                    style="margin-right: 7px"
                  ></i>
                  <span v-if="scope.row.fileName == editFileName" style="color:red;"> {{ scope.row.fileName }}&nbsp;&nbsp;编辑中……</span>
                  <span v-else> {{ scope.row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column min-width="80">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.directoryFlag == '1'"
                  size="mini"
                  plain
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div>
          <el-upload
            class="upload-demo"
            :action="uploadAction"
            multiple
            name="tempFile"
            :data="uploadData"
            :headers="headers"
            :on-success="handlerSuccess"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div></el-col
      >
    </el-row>
  </div>
</template>
<script>
import { cmstemplateList, cmstemplateDel, cmstemplateSave, getContents } from "@/api/cms/cmstemplate.js";
export default {
  data() {
    return {
      title: "",
      tableData: [],
      templatePath: "",
      editFileName: "",
      currentPath: "/",
      uploadAction: window.$conf.commonConf.baseUrl + "/cms/cmsTemplate/upload",
      uploadData: {
        title: "",
        dirPath: ""
      },
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem("token")
      },

      content: "",
      theme: '',
      num: 0,
      arr: [ //将brace/theme文件夹下的所有主题名字拷贝出来
        'ambiance',
        'chaos',
        'chrome',
        'clouds',
        'clouds_midnight',
        'cobalt',
        'crimson_editor',
        'dawn',
        'dracula',
        'dreamweaver',
        'eclipse',
        'github',
        'gob',
        'gruvbox',
        'idle_fingers',
        'iplastic',
        'katzenmilch',
        'kr_theme',
        'kuroir',
        'merbivore',
        'merbivore_soft',
        'monokai',
        'mono_industrial',
        'pastel_on_dark',
        'solarized_dark',
        'solarized_light',
        'sqlserver',
        'terminal',
        'textmate',
        'tomorrow',
        'tomorrow_night',
        'tomorrow_night_blue',
        'tomorrow_night_bright',
        'tomorrow_night_eighties',
        'twilight',
        'vibrant_ink',
        'xcode',
      ]

    }
  },
  created() {
    this.title = this.$route.query.title + '';
    if (this.title) {
      this.initInfo(this.title, true)
    }
  },
  components: {
    editor: require("vue2-ace-editor")
  },
  methods: {
    initInfo(title, isRoot) {
      let _that = this
      _that.tableData = []
      if (!isRoot) {
        _that.tableData.push({ directoryFlag: "3", fileName: "..(上级目录)" })
      }
      cmstemplateList({ title: title }).then((resp) => {
        if (resp.data) {
          _that.tableData = _that.tableData.concat(resp.data.files)
          _that.content = resp.data.contents
          _that.templatePath = resp.data.templatePath
          _that.editFileName = resp.data.fileName
        }
      });
    },
    save() {
      this.$confirm('确定要提交修改？', '提示', { type: 'warning' }).then(
        () => {
          let d = {
            contents: this.content,
            title: this.title,
            dirPath: this.currentPath == "/" ? "" : this.currentPath,
            fileName: this.editFileName
          }
          cmstemplateSave(d).then(res => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            } else {
              this.$msg({
                message: res.msg,
                type: "error",
              });
            }
          })
        })

    },
    back() {
      //返回
      this.$router.push({ path: "/cms/cmstemplate" });
    },
    //编辑器
    editorInit() {//初始化
      require("brace/ext/language_tools"); //language extension prerequsite...
      require("brace/mode/javascript"); //language
      // require("brace/theme/tomorrow_night");
      for (let i = 0; i < this.arr.length; i++) {//方便看哪个主题好看，循坏加载了所有主题，通过点击按钮切换
        require("brace/theme/" + this.arr[i])
      }
      require("brace/snippets/javascript"); //snippet
    },
    getValue() {//获取编辑器中的值
      console.log('编辑器中的值：' + this.$refs.aceEditor.editor.getValue())
      console.log('编辑器中第一个换行符的位置：' + this.$refs.aceEditor.editor.getValue().indexOf('\n'))
    },
    // pre() {//切换到上一个主题
    //   if (this.num == 0) {
    //     return
    //   }
    //   this.num--
    //   this.theme = this.arr[this.num]
    //   console.log('主题' + this.num + '__' + this.arr[this.num])
    // },
    // next() {//切换到下一个主题
    //   if (this.num == this.arr.length - 1) {
    //     return
    //   }
    //   this.num++
    //   this.theme = this.arr[this.num]
    //   console.log('主题' + this.num + '__' + this.arr[this.num])
    // },
    //编辑器 end

    handlerClick(row) {
      if ("0" == row.directoryFlag) {
        if (this.currentPath == "/") {
          this.currentPath = this.currentPath + row.fileName
        } else {
          this.currentPath = this.currentPath + "/" + row.fileName
        }
        this.initInfo(this.title + this.currentPath);
      } else if ("1" == row.directoryFlag) {
        let d = {
          title: this.title,
          dirPath: this.currentPath == "/" ? "" : this.currentPath,
          fileName: row.fileName
        }
        getContents(d).then(res => {
          if (res.code == 0) {
            this.content = res.data;
            this.editFileName = row.fileName
          } else {
            this.$msg({
              message: res.msg,
              type: "error",
            });
          }
        })
      } else if ("3" == row.directoryFlag) {
        if (this.currentPath.lastIndexOf("/") == 0) {
          this.currentPath = "/"
        } else {
          this.currentPath = this.currentPath.substring(0, this.currentPath.lastIndexOf("/"))
        }
        if (this.currentPath == "/") {
          this.initInfo(this.title, true);
        } else {
          this.initInfo(this.title + this.currentPath);
        }

      }
    },
    //删除
    handleDelete(row) {
      this.$confirm('确认删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("delete", row);
        let d = {
          title: this.title,
          dirPath: this.currentPath,
          fileName: row.fileName
        }
        cmstemplateDel(d).then((resp) => {
          if (resp.code == 0) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            if (this.currentPath == "/") {
              this.initInfo(this.title, true);
            } else {
              this.initInfo(this.title + this.currentPath);
            }
          } else {
            this.$msg({
              message: resp.msg,
              type: "error",
            });
          }
        });
      }).catch(() => {
      });
    },
    //文件上传成功回调
    handlerSuccess() {
      if (this.currentPath == "/") {
        this.initInfo(this.title, true);
      } else {
        this.initInfo(this.title + this.currentPath);
      }
    }
  },
  mounted() {
    this.editorInit();
    this.theme = this.arr[0]
    this.$refs.aceEditor.editor.setValue('')
    this.uploadData = {
      title: this.title,
      dirPath: this.currentPath
    }
  },
  watch: {
    currentPath(val) {
      this.uploadData.dirPath = val;
    }
  }
}
</script>

<style lang='scss' scoped>
</style>